package br.com.tecnoria.controllers
{
	import br.com.tecnoria.events.LoginEvent;
	import br.com.tecnoria.vo.UserVO;
	
	import flash.events.EventDispatcher;
	
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;
	
	import org.swizframework.utils.services.ServiceHelper;

	public class LoginController
	{
		[Inject("loginRemote")]
		public var remote:RemoteObject;
		
		[Inject]
		public var serviceHelper:ServiceHelper;
		
		[Bindable]
		public var user:UserVO;
		
		[Dispatcher]
		public var dispatcher:EventDispatcher;
		
		
		/**
		 * Call Function
		 */
		
		[EventHandler(event="LoginEvent.DO_LOGIN", properties="user")]
		public function doLogin(user:UserVO):void
		{
			serviceHelper.executeServiceCall(remote.doLogin(user), onDoLogin, onFault);
		}
		
		
		
		/**
		 * Result Function
		 */
		
		public function onDoLogin(result:ResultEvent):void
		{
			if (result.result.status == true) 
			{
				user = result.result.user as UserVO;
				dispatcher.dispatchEvent(new LoginEvent(LoginEvent.LOGIN_OK));
			}
			else
			{
				dispatcher.dispatchEvent(new LoginEvent(LoginEvent.LOGIN_FAIL));
			}
		}
		
		
		
		/**
		 * Fault Function
		 */
		
		public function onFault(result:FaultEvent):void
		{
			Alert.show(result.fault.toString(), "Erro");
		}
	}
}